/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.app.ad.service.impl;

import me.zhengjie.modules.app.ad.domain.AdInfo;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.app.ad.repository.AdInfoRepository;
import me.zhengjie.modules.app.ad.service.AdInfoService;
import me.zhengjie.modules.app.ad.service.dto.AdInfoDto;
import me.zhengjie.modules.app.ad.service.dto.AdInfoQueryCriteria;
import me.zhengjie.modules.app.ad.service.mapstruct.AdInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.SecurityUtils;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Haojie Li
* @date 2021-03-01
**/
@Service
@RequiredArgsConstructor
public class AdInfoServiceImpl implements AdInfoService {

    private final AdInfoRepository adInfoRepository;
    private final AdInfoMapper adInfoMapper;

    @Override
    public Map<String,Object> queryAll(AdInfoQueryCriteria criteria, Pageable pageable){
        Page<AdInfo> page = adInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(adInfoMapper::toDto));
    }

    @Override
    public List<AdInfoDto> queryAll(AdInfoQueryCriteria criteria){
        return adInfoMapper.toDto(adInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AdInfoDto findById(String id) {
        AdInfo adInfo = adInfoRepository.findById(id).orElseGet(AdInfo::new);
        ValidationUtil.isNull(adInfo.getId(),"AdInfo","id",id);
        return adInfoMapper.toDto(adInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AdInfoDto create(AdInfo resources) {
        resources.setId(IdUtil.simpleUUID()); 
        resources.setCreateBy(SecurityUtils.getCurrentUsername());
        resources.setCreateTime(LocalDateTime.now());
        resources.setIsEnable(1);
        return adInfoMapper.toDto(adInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AdInfo resources) {
    	resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
    	
    	AdInfo adInfo = adInfoRepository.findById(resources.getId()).orElseGet(AdInfo::new);
        ValidationUtil.isNull( adInfo.getId(),"AdInfo","id",resources.getId());
        adInfo.copy(resources);
        adInfoRepository.save(adInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String id : ids) {
            adInfoRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AdInfoDto> all, HttpServletResponse response) throws IOException {
    	DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<Map<String, Object>> list = new ArrayList<>();
        for (AdInfoDto adInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("广告名称", adInfo.getAdTitle());
            map.put("广告资源地址", adInfo.getAdResourceUrl());
            map.put("广告资源类型", adInfo.getAdResourceType());
            map.put("广告显示时长（以秒为单位）", adInfo.getAdDisplayTime());
            map.put("创建者", adInfo.getCreateBy());
            map.put("更新者", adInfo.getUpdateBy());
            map.put("是否展示", adInfo.getIsDefault() == "1" ? "展示" : "不展示");
            map.put("创建时间", adInfo.getCreateTime()  == null ? "" : dtf.format(adInfo.getCreateTime()));
            map.put("更新时间", adInfo.getUpdateTime() == null ? "" : dtf.format(adInfo.getUpdateTime()));
            map.put("数据状态", adInfo.getIsEnable());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

	@Transactional(rollbackFor = Exception.class)
	@Override
	public void updateIsDefault(AdInfo resources) {
		// TODO Auto-generated method stub
		adInfoRepository.updateAllDefault();
		
		resources.setUpdateBy(SecurityUtils.getCurrentUsername());
    	resources.setUpdateTime(LocalDateTime.now());
    	
    	AdInfo adInfo = adInfoRepository.findById(resources.getId()).orElseGet(AdInfo::new);
        ValidationUtil.isNull( adInfo.getId(),"AdInfo","id",resources.getId());
        adInfo.copy(resources);
        adInfoRepository.save(adInfo);
	}
}